package net.maku.framework.common.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class DownloadUtils {
    public static void wrapDownloadFile(InputStream inputStream, String displayFilename, HttpServletResponse response)
    {
        wrapDownloadHttpResponse(displayFilename, response);
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            int len;
            byte[] buffer = new byte[2048];
            while ((len = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }

            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void wrapDownloadHttpResponse(String displayFilename, HttpServletResponse response)
    {
        response.addHeader("Cache-Control", "no-cache");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
        response.addDateHeader("Expires", 0);
        response.setCharacterEncoding("UTF-8");

        String suffix = displayFilename.substring(displayFilename.lastIndexOf(".") + 1);
        String contentType = null;
        if ("XLSX".equalsIgnoreCase(suffix)){
            contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        }else{
            contentType = "application/vnd.ms-excel";
        }
        response.setContentType(contentType);
        try
        {
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(displayFilename, "UTF-8"));
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
    }
}
